package com.jeecms.wicool.action.car;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.upload.FileRepository;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.car.CarAdviser;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.car.CarAdviserMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.util.ConstantUtil;
import com.jeecms.wicool.util.HttpRequestUtil;

@Controller
public class CarAdviserAct {
	private static final Logger log = LoggerFactory.getLogger(CarAdviserAct.class);

	@RequestMapping("/carAdviser/v_list.do")
	public String list(String name,Short level,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(name,level,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<CarAdviser> listCarAdviser =(List<CarAdviser>) pagination.getList();
		List<Dictionary2> listAdviserType=DicMng.getList("adviser_type");
		Map<String,String> map = new HashMap<String,String>();
		 for(Dictionary2 d : listAdviserType){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 }
		 for(CarAdviser p : listCarAdviser){
			 if(map.containsKey(p.getAdviserType().toString())){
				 p.setAdviserTypeName(map.get(p.getAdviserType().toString()));
			 }
		 }
		model.addAttribute("pagination", pagination);
		model.addAttribute("name", name);
		model.addAttribute("level", level);
		return "car/list_carAdviser";
	}
	
	@RequestMapping("/carAdviser/v_edit.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarAdviser carAdviser = manager.findById(id);
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> listAdviserType=DicMng.getList("adviser_type");
		model.addAttribute("listAdviserType", listAdviserType);
		model.addAttribute("carAdviser",carAdviser);
		model.addAttribute("listShop",listShop);
		return "car/edit_carAdviser";
	}
	@RequestMapping("/carAdviser/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarAdviser carAdviser = manager.findById(id);
		List<Dictionary2> listAdviserType=DicMng.getList("adviser_type");
		if(listAdviserType!=null){
			for(Dictionary2 d :listAdviserType){
				if(carAdviser.getAdviserType()==Integer.parseInt(Short.toString(d.getDicCode()))){
					carAdviser.setAdviserTypeName(d.getDicName());
				}
			}
		}
		model.addAttribute("carAdviser",carAdviser);
		return "car/view_carAdviser";
	}
	@RequestMapping("/carAdviser/o_save.do")
	public String save(CarAdviser bean, Integer shopId,HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.save(bean,shopId);
		log.info("save CarAdviser id={}", bean.getId());
		cmsLogMng.operating(request, "CarAdviser.log.save",  "id=" + bean.getId());
		String qRURLStr = ConstantUtil.weixingQR+bean.getId(); 
		String QRstr = HttpRequestUtil.HttpRequest(qRURLStr);
		String QRURL = StringUtils.EMPTY;
		if (StringUtils.isNotEmpty(QRstr)) {
			//解析返回的字符串
			JSONObject ct;
			try {
				ct = new JSONObject(QRstr);
				QRURL = ct.getString("url") == null ? StringUtils.EMPTY : ct.getString("url").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				log.info("微信接口调用失败", bean.getId());
			}
			
			//更新字段
			if (StringUtils.isNotEmpty(QRURL)) {
				//生成微信二维图
				String qRpathString = fileRepository.CreateQR("QRimg","QR_"+bean.getId(), "png", QRURL);
				if (StringUtils.isNotEmpty(qRpathString)) {
					bean.setGravatar(request.getContextPath()+"/"+qRpathString);
					bean=manager.update(bean,shopId);
					log.info("微信接口调用成功", bean.getId());
				}
			}
		}else {
			log.info("微信接口调用失败", bean.getId());
		}
		
		return "redirect:v_list.do";
	}
	@RequestMapping("/carAdviser/o_update.do")
	public String update(CarAdviser bean,Integer shopId,String q_name,Short q_level,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		bean=manager.update(bean,shopId);
		model.addAttribute("message", "global.success");
		log.info("update CarAdviser success. id={}", bean.getId());
		cmsLogMng.operating(request, "CarAdviser.log.update",  "id=" + bean.getId());
		return list(q_name,q_level,pageNo,request, model);
	}
	
	@RequestMapping("/carAdviser/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		CarAdviser carAdviser = new CarAdviser();
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> listAdviserType=DicMng.getList("adviser_type");
		model.addAttribute("listAdviserType", listAdviserType);
		model.addAttribute("carAdviser", carAdviser);
		model.addAttribute("listShop", listShop);
		return "car/add_carAdviser";
	}
	

	@RequestMapping("/carAdviser/o_delete.do")
	public String delete(Integer[] ids, String name,Short level,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarAdviser[] beans = manager.deleteByIds(ids);
		for (CarAdviser bean : beans) {
			log.info("delete CarAdviser id={}", bean.getId());
			cmsLogMng.operating(request, "CarAdviser.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getName());
		}
		return list(name,level,pageNo, request, model);
	}
	
	@RequestMapping("/carAdviser/o_createRQ.do")
	public String createRQ(Integer id, String name,Short level,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		Integer ids[] = {id};
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarAdviser bean = manager.findById(id);
		String QRStr = generateQR(bean.getId(),request);
		if (StringUtils.isNotEmpty(QRStr)) {
			bean.setGravatar(QRStr);
			manager.update(bean, bean.getShop().getId());
			log.info("二维码生成成功", id);
		}else {
			log.info("二维码生成失败", id);
		}
		return list(name,level,pageNo, request, model);
	}
	
	private WebErrors validateSave(CarAdviser bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		CarAdviser entity = manager.findById(id);
		if (errors.ifNotExist(entity, CarAdviser.class, id)) {
			return true;
		}
		return false;
	}
	private String generateQR(Integer id,HttpServletRequest request){
		String qRURLStr = ConstantUtil.weixingQR+id; 
		String QRstr = HttpRequestUtil.HttpRequest(qRURLStr);
		String QRURL = StringUtils.EMPTY;
		if (StringUtils.isNotEmpty(QRstr)) {
			//解析返回的字符串
			JSONObject ct;
			try {
				ct = new JSONObject(QRstr);
				QRURL = ct.getString("url") == null ? StringUtils.EMPTY : ct.getString("url").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				log.info("微信接口调用失败", id);
			}
			
			if (StringUtils.isNotEmpty(QRURL)) {
				//生成微信二维图
				String qRpathString = fileRepository.CreateQR("QRimg","QR_"+id, "png", QRURL);
				return StringUtils.isNotEmpty(qRpathString)?request.getContextPath()+"/"+qRpathString:StringUtils.EMPTY;
			}else {
				return StringUtils.EMPTY;
			}
		}else {
			return StringUtils.EMPTY;
		}
	}
	@Autowired
	private CarAdviserMng manager;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private FileRepository fileRepository;
}
